<?php

class SJB_ComplexVideoFileType extends SJB_UploadVideoFileType
{
	private $fieldID;
	private $complexEnum;
	private $values;
	private $files;
	
	function __construct($property_info)
	{
		parent::SJB_UploadVideoFileType($property_info);
	}

	function isValid()
	{
		$upload_manager = new SJB_UploadFileManager();
		if (!empty($this->property_info['max_file_size'])) 
			$upload_manager->setMaxFileSize($this->property_info['max_file_size']);

		if ($this->getComplexParent()) {
			$upload_manager->isValidUploadedFile($this->getComplexParent(), $this->property_info['id']);
		} else if ($upload_manager->isValidUploadedFile($this->property_info['id'])) {
			return true;
		}
		
		$this->fieldID = $this->property_info['id'];

		if ($this->getComplexParent()) {
			if (!isset($_FILES[$this->getComplexParent()]['name']) || $_FILES[$this->getComplexParent()]['name'] == '') {
				return true;
			}
		}
		elseif (!isset($_FILES[$this->fieldID]['name']) || $_FILES[$this->fieldID]['name'] == '') {
			return true;
		}

		foreach ($_FILES[$this->getComplexParent()]['name'][$this->fieldID] as $complexEnum => $videoFileInfo) {
			
			if (!isset( $_FILES[$this->getComplexParent()]['name'][$this->fieldID][$complexEnum]) ||  $_FILES[$this->getComplexParent()]['name'][$this->fieldID][$complexEnum] == '')
				continue;
			$file_id = $this->getComplexParent() . ':' . $this->property_info['id'] . ':' . $complexEnum . '_' . $this->object_sid . '_tmp';
			
			$_FILES[$this->fieldID]['name']		= $_FILES[$this->getComplexParent()]['name'][$this->fieldID][$complexEnum];
			$_FILES[$this->fieldID]['error']	= $_FILES[$this->getComplexParent()]['error'][$this->fieldID][$complexEnum];
			$_FILES[$this->fieldID]['type']		= $_FILES[$this->getComplexParent()]['type'][$this->fieldID][$complexEnum];
			$_FILES[$this->fieldID]['size']		= $_FILES[$this->getComplexParent()]['size'][$this->fieldID][$complexEnum];
			$_FILES[$this->fieldID]['tmp_name']	= $_FILES[$this->getComplexParent()]['tmp_name'][$this->fieldID][$complexEnum];
			if (isset($_FILES[$this->getComplexParent()]['import'][$this->fieldID][$complexEnum]))
				$_FILES[$this->fieldID]['import'] = $_FILES[$this->getComplexParent()]['import'][$this->fieldID][$complexEnum];
			
			SJB_DB::query('DELETE FROM uploaded_files WHERE id=?s', $file_id);

			$this->property_info['value'] = $file_id;
			$upload_manager = new SJB_UploadFileManager();
			$upload_manager->setFileGroup('video');
			$upload_manager->setUploadedFileID($file_id);


			// CHECK FILE BEFORE UPLOAD
			if (!empty($this->property_info['max_file_size']))
				$upload_manager->setMaxFileSize($this->property_info['max_file_size']);

			if ($this->getComplexParent()) {
				$upload_manager->isValidUploadedFile($this->getComplexParent(), $this->property_info['id']);
			}
			else if ($upload_manager->isValidUploadedFile($this->property_info['id'])) {
				return true;
			}



			$saved_file_name = $upload_manager->uploadFile($this->fieldID);

			

			if ($saved_file_name === false) {
				return $upload_manager->getError();
			}

			$filename = SJB_BASE_DIR . '/files/video/' . $saved_file_name;
			$base_name = substr($saved_file_name, 0, strrpos($saved_file_name, '.'));

			$ext = substr($saved_file_name, 1 + strrpos($saved_file_name, '.'));

			if ($ext == 'flv') {
				$t_outfile = SJB_BASE_DIR . '/files/video/' . $base_name . '.flv_';
				$outfile = SJB_BASE_DIR . '/files/video/' . $base_name . '.flv';
				$this->convert_media($filename, $t_outfile, 320, 240, 32, 22050);

				if (!$upload_manager->fileExists($base_name . '.flv_', true)) {
					$upload_manager->deleteUploadedFileByID($file_id);
					return $upload_manager->getError();
				}

				$upload_manager->deleteUploadedFileByID($file_id);
				rename($t_outfile, $outfile);
			}
			else {
				$outfile = SJB_BASE_DIR . '/files/video/' . $base_name . '.flv';
				$this->convert_media($filename, $outfile, 320, 240, 32, 22050);

				if (!$upload_manager->fileExists($base_name . '.flv', true)) {
					$upload_manager->deleteUploadedFileByID($file_id);
					return $upload_manager->getError();
				}

				$upload_manager->deleteUploadedFileByID($file_id);
			}

			$filename = SJB_BASE_DIR . '/files/video/' . $base_name . '.flv';
			$img = SJB_BASE_DIR . '/files/video/' . $base_name . '.png';
			$this->grab_image($filename, $img, "00:00:03", 'png', 320, 240);

			$upload_manager->registNewFile($file_id, $base_name . '.flv');
		
		}
		
		return true;
			
	}
	
	/**
	 *
	 * @global string SJB_BASE_DIR
	 * @param string $saved_file_name
	 * @param SJB_UploadFileManager $upload_manager
	 * @param string $file_id
	 * @return boolean
	 */
	function moveFile($saved_file_name, $upload_manager, $file_id)
	{
		$filename = SJB_BASE_DIR.'/files/video/'.$saved_file_name;
		$base_name = substr($saved_file_name,0, strrpos($saved_file_name, "."));
		
		$ext = substr($saved_file_name,1 + strrpos($saved_file_name, "."));
		
		if ($ext == 'flv') {
			$t_outfile = SJB_BASE_DIR.'/files/video/'.$base_name.'.flv_';
			$outfile = SJB_BASE_DIR.'/files/video/'.$base_name.'.flv';
			$this->convert_media($filename, $t_outfile, 320, 240, 32, 22050);
		
			if(!$upload_manager->fileExists($base_name.'.flv_',true)) {
				$upload_manager->deleteUploadedFileByID($file_id);
				return $upload_manager->getError();
			}
						
			$upload_manager->deleteUploadedFileByID($file_id);
			rename($t_outfile,$outfile);
		}
		else 
		{
			$outfile = SJB_BASE_DIR.'/files/video/'.$base_name.'.flv';
			$this->convert_media($filename, $outfile, 320, 240, 32, 22050);
		
			if(!$upload_manager->fileExists($base_name.'.flv',true)) {
				$upload_manager->deleteUploadedFileByID($file_id);
				return $upload_manager->getError();
			}
		
			$upload_manager->deleteUploadedFileByID($file_id);
		}

		$filename = SJB_BASE_DIR . '/files/video/' . $base_name . '.flv';
		$img = SJB_BASE_DIR . '/files/video/' . $base_name . '.png';
		$this->grab_image($filename, $img, "00:00:03", 'png', 320, 240);

		$upload_manager->registNewFile($file_id, $base_name . '.flv');

		return true;
	}
	
	/**
	 * if several files posted
	 * 
	 * @global string SJB_BASE_DIR
	 * @param array $saved_file_names
	 * @param SJB_UploadFileManager $upload_manager
	 * @param string $file_id
	 * @return boolean
	 */
	function moveFiles($saved_file_names, $upload_manager, $file_id)
	{
		foreach ($saved_file_names as $key => $saved_file_name) {
			
			$file_id = $file_id . '_' . $key;
			
			$filename	= SJB_BASE_DIR.'/files/video/'.$saved_file_name;
			$base_name	= substr($saved_file_name,0, strrpos($saved_file_name, "."));
			$ext		= substr($saved_file_name,1 + strrpos($saved_file_name, "."));

			if ($ext == 'flv') {
				$t_outfile	= SJB_BASE_DIR.'/files/video/'.$base_name.'.flv_';
				$outfile	= SJB_BASE_DIR.'/files/video/'.$base_name.'.flv';
				
				$this->convert_media($filename, $t_outfile, 320, 240, 32, 22050);

				if(!$upload_manager->fileExists($base_name.'.flv_',true)) {
					$upload_manager->deleteUploadedFileByID($file_id);
					return $upload_manager->getError();
				}

				$upload_manager->deleteUploadedFileByID($file_id);
				rename($t_outfile,$outfile);
			}
			else 
			{
				$outfile	= SJB_BASE_DIR.'/files/video/'.$base_name.'.flv';
				$this->convert_media($filename, $outfile, 320, 240, 32, 22050);

				if(!$upload_manager->fileExists($base_name.'.flv',true)) {
					$upload_manager->deleteUploadedFileByID($file_id);
					return $upload_manager->getError();
				}

				$upload_manager->deleteUploadedFileByID($file_id);
			}

			$filename = SJB_BASE_DIR . '/files/video/' . $base_name . '.flv';
			$img = SJB_BASE_DIR . '/files/video/' . $base_name . '.png';

			$this->grab_image($filename, $img, "00:00:03", 'png', 320, 240);
			$upload_manager->registNewFile($file_id, $base_name . '.flv');
		}
		return true;
	}
	
	function getSQLValue()
	{
		$file_id = $this->getComplexParent() . ':' . $this->property_info['id'] . ':' . $this->complexEnum . '_' . $this->object_sid;
		$file_id_tmp = $this->getComplexParent() . ':' . $this->property_info['id'] . ':' . $this->complexEnum . '__tmp';
		$this->property_info['value'] = $file_id;
		SJB_DB::query('UPDATE uploaded_files SET id = ?s WHERE  id = ?s LIMIT 1', $file_id, $file_id_tmp);
		if (SJB_UploadFileManager::doesFileExistByID($file_id))
			return "'{$file_id}'";
		return "''";
	}
	
	function convert_media($filename, $outfile, $width, $height, $bitrate, $samplingrate)
	{
		$size = $width . "x" . $height;
		$cmd = "ffmpeg -i \"{$filename}\" -ar {$samplingrate} -ab {$bitrate} -f flv -s {$size} \"{$outfile}\" 2>&1";
		
		$ret = array();
		exec($cmd, $ret);
		
		if (SJB_HelperFunctions::debugModeIsTurnedOn()) {
			$debug = array (
				'media'		=>	print_r($cmd,1),
				'result'	=>	print_r($ret,1)
			);
			SJB_HelperFunctions::debugInfoPush($debug, 'COMPLEX_VIDEO_CONVERT_MEDIA');
		}
		
		return $ret;
	}

	function getPropertyVariablesToAssign()
	{
		$upload_manager = new SJB_UploadFileManager();
		$upload_manager->setFileGroup('video');
		if (!empty($this->values))
			$this->property_info['value'] = $this->values;
		if (is_array($this->property_info['value'])) {
			$value = array();
			foreach ($this->property_info['value'] as $key => $fileId) {
				$value[$key] = array(
							'file_url' => $upload_manager->getUploadedFileLink($fileId),
							'file_name' => $upload_manager->getUploadedFileName($fileId),
							'saved_file_name' => $upload_manager->getUploadedSavedFileName($fileId),
							'file_id' => $fileId
						);
			}
			return array(
				'id' 	=> $this->property_info['id'],
				'filesInfo' => $value,
				'value' => $value
			);
		}

		return array(
						'id' 	=> $this->property_info['id'],
						'value'	=> array(
							'file_url' => $upload_manager->getUploadedFileLink($this->property_info['value']),
							'file_name' => $upload_manager->getUploadedFileName($this->property_info['value']),
							'saved_file_name' => $upload_manager->getUploadedSavedFileName($this->property_info['value']),
							'file_id' => $this->property_info['value'],
						),
					);
	}
	
	function setComplexEnum($value) 
	{
		$this->complexEnum = $value;
	}
	
	
	function getValue()
	{
        $upload_manager = new SJB_UploadFileManager();
		
		if (!empty($_FILES[$this->getComplexParent()]['name'][$this->property_info['id']])) {
			
			if (!empty($this->property_info['value']))
				$this->values = $this->property_info['value'];
			$files = $_FILES[$this->getComplexParent()]['name'][$this->property_info['id']];
			$this->files = $_FILES[$this->getComplexParent()];
			return $files;
			
		}
		elseif (is_array($this->property_info['value'])) {
			
			$value = array();
			foreach ($this->property_info['value'] as $key => $fileId) {
				$value[$key] = array(
							'file_url' => $upload_manager->getUploadedFileLink($fileId),
							'file_name' => $upload_manager->getUploadedFileName($fileId),
							'saved_file_name' => $upload_manager->getUploadedSavedFileName($fileId),
							'file_id' => $fileId,
						);
			}
			return $value;
		}
		return array(
			'file_url' 	=> $upload_manager->getUploadedFileLink($this->property_info['value']),
			'file_name' => $upload_manager->getUploadedFileName($this->property_info['value']),
			'saved_file_name' => $upload_manager->getUploadedSavedFileName($this->property_info['value']),
			'file_id' => $this->property_info['value'],
		);
	}
	
	function isEmpty() 
	{
		if ($this->getComplexParent()) {
			return !SJB_UploadFileManager::isFileReadyForUpload($this->getComplexParent());
		}
		return parent::isEmpty() && !SJB_UploadFileManager::isFileReadyForUpload($this->property_info['id']);
	}
}

